﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Eacademy.Domain.Abstractions;
using Eacademy.Domain.Models;
using Eacademy.Library.Actions;
using Eacademy.Library.Helpers;
using Eacademy.Library.Membership;
using Elmah;

namespace Eacademy.Areas.Student.Controllers
{
    [ProfileControllerFilter]
    public class ProfileController : Controller
    {
        //
        // GET: /Mentor/Profile/
        private IStudentRepository _studentRepository;
        private IUserRepository _userRepository;

        private static CustomMembershipProvider Provider
        {
            get
            {
                return (CustomMembershipProvider)Membership.Provider;
            }
        }

        private string SavePath
        {
            get
            {
                return String.Format(@"{0}", Server.MapPath(AppSettings.AvatarImageDirectory));
            }
        }

        public ProfileController(IStudentRepository studentRepository,IUserRepository userRepository)
        {
            _studentRepository = studentRepository;
            _userRepository = userRepository;
        }

        public ActionResult Edit()
        {
            AdminStudentsViewModel adminStudentsViewModel = _studentRepository.GetStudentByUserId((int)Provider.User.UserId);
            string relaveFilePath = AppSettings.AvatarImageDirectory.Replace("~", "");
            adminStudentsViewModel.ThumbImagePathName = String.Format("{0}{1}", relaveFilePath, adminStudentsViewModel.ThumbImageName);
            return View(adminStudentsViewModel);
        }

        [HttpPost]
        public ActionResult Edit(AdminStudentsViewModel student, string filename)
        {
            string fileName = Path.GetFileNameWithoutExtension(filename);
            string extension = Path.GetExtension(filename);

            student.ThumbImageName = String.Format("{0}_thumb{1}", fileName, extension);

            UpdateUserUploadedFiles(filename, student);

            if (_studentRepository.UpdateStudent(student)!= null)
            {
                this.FlashDone("Your profile has been updated");
            }
            else
            {
                this.FlashError("There was an error updating your profile");
            }
            return Redirect("/student/home");
        }

        [HttpPost]
        public ActionResult ChangePassword(PasswordViewModel passwordViewModel)
        {
            var user = _userRepository.GetUserByUserId(Provider.User.UserId);
            if (!String.IsNullOrEmpty(passwordViewModel.Password))
            {

                if (_userRepository.ResetPassword(passwordViewModel.Password, (int)user.UserId, user.PasswordSalt))
                {
                    return Content("Password was successfully changed");
                }
            }
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Content("Password change error");
        }

        [HttpPost]
        public ActionResult UploadImage(string authtoken, string si, HttpPostedFileBase fileData)
        {
            string savePath = SavePath;

            string relaveFilePath = AppSettings.AvatarImageDirectory.Replace("~", "");

            string imageUrl = String.Empty;

            if (Directory.Exists(savePath) == false)
            {
                Directory.CreateDirectory(savePath);
            }

            var file = fileData;
            string fileExt = Path.GetExtension(file.FileName).ToLower();
            string fileWoExt = KeyGenerator.GenerateId();
            string fileName = string.Format("{0}{1}", fileWoExt, fileExt);

            var fileExtensions = new String[]{
               ".gif",".png",".jpg",".jpeg"
            };

            if (fileName != string.Empty)
            {
                try
                {
                    if (fileExtensions.ToList().Contains(fileExt))
                    {
                        if (System.IO.File.Exists(savePath + fileName) == true)
                        {
                            System.IO.File.Delete(savePath + fileName);
                        }

                        fileName = string.Format("{0}-{1}", Provider.User.Identification, fileName);

                        string pathfilename = savePath + fileName;
                        file.SaveAs(pathfilename);

                        string thumbnailFilename = String.Format("{0}_thumb{1}", fileWoExt, fileExt);

                        thumbnailFilename = String.Format("{0}-{1}", Provider.User.Identification, thumbnailFilename);

                        string thumbnailPathfilename = savePath + thumbnailFilename;

                        imageUrl = relaveFilePath + thumbnailFilename;

                        int width = 100;
                        int height = 100;

                        ImageUtilities.ResizeImage(pathfilename, thumbnailPathfilename, width, height, false);

                    }
                    else
                    {
                        throw new InvalidDataException("The file is not supported");
                    }
                }
                catch (Exception ex)
                {
                    ErrorSignal.FromCurrentContext().Raise(ex);
                }
            }
            return Json(new { url = imageUrl, filename = fileName });
        }

        [NonAction]
        private void UpdateUserUploadedFiles(string filename, AdminStudentsViewModel student)
        {
            string savePath = String.Format(@"{0}", Server.MapPath(AppSettings.AvatarImageDirectory));

            if (filename.Contains("-"))
            {
                //Remove userid from file name of thumbnail and original file

                string newImageName = filename.Substring(filename.IndexOf("-") + 1);
                System.IO.File.Copy(Path.Combine(savePath, filename), Path.Combine(savePath, newImageName), true);

                string newThumbName = student.ThumbImageName.Substring(student.ThumbImageName.IndexOf("-") + 1);
                System.IO.File.Copy(Path.Combine(savePath, student.ThumbImageName), Path.Combine(savePath, newThumbName), true);

                String[] userUploadedImages = Directory.GetFiles(savePath, Provider.User.Identification + "-*");

                //Delete other files with userid on it

                foreach (String file in userUploadedImages)
                {
                    System.IO.File.Delete(file);
                }

                //Update file details

                student.ThumbImageName = newThumbName;
            }
        }
    }
}
